package com.quan.mall.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quan.commons.core.biz.support.MyBaseServiceImpl;
import com.quan.commons.core.exception.BizException;
import com.quan.commons.core.utils.PageUtils;
import com.quan.mall.commons.vo.UmsMemberVo;
import com.quan.mall.entity.FmsMemberWallet;
import com.quan.mall.entity.UmsMember;
import com.quan.mall.service.FmsMemberWalletService;
import com.quan.mall.service.UmsMemberService;
import com.quan.system.commons.vo.SysUserVo;
import com.quan.system.entity.SysUser;
import com.quan.system.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.quan.mall.commons.vo.WmsAgentInfoVo;
import com.quan.mall.entity.WmsAgentInfo;
import com.quan.mall.mapper.WmsAgentInfoMapper;
import com.quan.mall.service.WmsAgentInfoService;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service
public class WmsAgentInfoServiceImpl extends MyBaseServiceImpl<WmsAgentInfoMapper, WmsAgentInfo> implements WmsAgentInfoService {

    @Autowired
	private WmsAgentInfoMapper mapper;

    @Autowired
	private UmsMemberService umsMemberService;

    @Autowired
	private SysUserService sysUserService;

    @Autowired
	private FmsMemberWalletService fmsMemberWalletService;

    @Transactional
    @Override
    public boolean save(WmsAgentInfo entity) {
        if(super.hasExist("phone", entity.getPhone(), WmsAgentInfo.class)) {
            throw new BizException("创建代理商失败，手机号号已存在");
        }

        if(this.umsMemberService.hasExist("mobile", entity.getPhone(), UmsMember.class)) {
            throw new BizException("创建代理商失败，手机号已存在商场会员中，无法创建");
        }

        if(super.hasExist("phone", entity.getPhone(), WmsAgentInfo.class)) {
            throw new BizException("创建代理商失败，手机号已存在系统用户中，无法创建");
        }

        final boolean save = super.save(entity);

        if(save) {
            // 创建商场会员
            UmsMemberVo umsMemberVo = new UmsMemberVo();
            umsMemberVo.setAgentId(entity.getId());
            umsMemberVo.setNickname(entity.getName());
            umsMemberVo.setMobile(entity.getPhone());
            umsMemberVo.setType(5);
            this.umsMemberService.saveMember(umsMemberVo);

            SysUserVo userVo = new SysUserVo();
            userVo.setAgentId(entity.getId());
            userVo.setRealname(entity.getName());
            userVo.setUsername(entity.getPhone());
            userVo.setMobile(entity.getPhone());
            userVo.setType(2);// 代理商用户
            this.sysUserService.saveUser(userVo);

        }

        return false;
    }

    @Transactional
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        boolean flag = super.removeByIds(idList);

        idList.forEach(id -> {
            // 获取代理商会员
            final UmsMember agentMember = this.umsMemberService.getOne(new QueryWrapper<UmsMember>().eq("agent_id", id).eq("type", 5));

            // 删除系统用户
            this.sysUserService.remove(new QueryWrapper<SysUser>().eq("agent_id", id));
            // 删除会员
            this.umsMemberService.removeById(agentMember.getId());
            // 删除会员钱包
            this.fmsMemberWalletService.remove(new QueryWrapper<FmsMemberWallet>().eq("member_id", agentMember.getId()));

        });

        return flag;
    }

    @Override
    public List<WmsAgentInfoVo> queryList(PageUtils pageUtils, WmsAgentInfoVo vo) {
        QueryWrapper<WmsAgentInfo> queryWrapper = new QueryWrapper<WmsAgentInfo>(vo);

        List<WmsAgentInfo> list = super.list(pageUtils, queryWrapper);
        List<WmsAgentInfoVo> collect = list.stream().map(item -> {
            WmsAgentInfoVo bean = new WmsAgentInfoVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, WmsAgentInfoVo vo) {
        QueryWrapper<WmsAgentInfo> queryWrapper = new QueryWrapper<WmsAgentInfo>(vo);

        if(StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("phone", vo.getKeyword())
                .or().like("company_name", vo.getKeyword());
            });
        }

        final IPage<WmsAgentInfo> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<WmsAgentInfo> records = page.getRecords();

        final List<WmsAgentInfo> collect = records.stream().map((item) -> {
            WmsAgentInfoVo bean = new WmsAgentInfoVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }

    @Override
    public WmsAgentInfo getAgentByPhone(String mobile) {
        QueryWrapper<WmsAgentInfo> queryWrapper = new QueryWrapper<WmsAgentInfo>();
        queryWrapper.eq("phone", mobile);
        return super.getOne(queryWrapper, false);
    }
}